using System;
using System.Diagnostics;
using System.Drawing;
using System.Net;
using System.Text;
using System.Windows.Forms;

namespace BibleScreen
{
    internal class ScreenSaverForm : Form
    {
        private readonly ImageSource imageSource;
        private readonly ImageUI imageUI;
        private readonly BibleTextSource bibleTextSource;
        private readonly BibleTextUI bibleTextUI;

        private bool isActive;
        private Point mouseLocation = Point.Empty;


        public ScreenSaverForm()
        {
            bibleTextSource = new BibleTextSource();
            imageSource = new ImageSource();

            InitializeComponent();

            bibleTextUI = new BibleTextUI(Bounds, bibleTextSource);
            imageUI = new ImageUI(Bounds, imageSource, this);
        }

        private void InitializeComponent()
        {
            SuspendLayout();

            // Double buffering
            SetStyle(
                ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);

            DoubleBuffered = true;
            CenterToScreen();
            Bounds = Screen.PrimaryScreen.Bounds;
            WindowState = FormWindowState.Maximized;

            BackColor = Color.Black;
            //Opacity = .2;

            FormBorderStyle = FormBorderStyle.None;

            Name = "ScreenSaver";

#if !DEBUG
            TopMost = true;
            ShowInTaskbar = false;
#endif

            ResumeLayout(false);

            Capture = true;
            Cursor.Hide();

            MouseMove += ScreenSaverForm_MouseMove;
            KeyDown += ScreenSaverForm_KeyDown;
            MouseDown += ScreenSaverForm_MouseDown;

            var client = new WebClient {Encoding = Encoding.UTF8};
            client.DownloadStringCompleted += client_DownloadStringCompleted;
            client.DownloadStringAsync(new Uri(@"http://files.geekjuggler.net/dailybread-message"));
        }


        protected override void OnPaint(PaintEventArgs e)
        {
            imageUI.DoPaint(e);
            bibleTextUI.DoPaint(e);
        }

        public override void Refresh()
        {
            if (InvokeRequired)
            {
                try
                {
                    Invoke(new RefreshCallback(Refresh));
                }
                catch (InvalidOperationException)
                {
                }
                return;
            }
            base.Refresh();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (bibleTextUI != null)
                    bibleTextUI.Dispose();
                if (imageUI != null)
                    imageUI.Dispose();
                if (imageSource != null)
                    imageSource.Dispose();
            }
            base.Dispose(disposing);
        }

        private void ScreenSaverForm_MouseMove(object sender, MouseEventArgs e)
        {
            // Set IsActive and MouseLocation only the first time this event is called.
            if (!isActive)
            {
                mouseLocation = MousePosition;
                isActive = true;
            }
            else
            {
                // If the mouse has moved significantly since first call, close.
                if ((Math.Abs(MousePosition.X - mouseLocation.X) > 10) ||
                    (Math.Abs(MousePosition.Y - mouseLocation.Y) > 10))
                {
                    Close();
                }
            }
        }

        private void ScreenSaverForm_KeyDown(object sender, KeyEventArgs e)
        {
            Close();
        }

        private void ScreenSaverForm_MouseDown(object sender, MouseEventArgs e)
        {
            Close();
        }

        private void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null) 
                return;

            var lines = e.Result.Split(new[] {"\n", "\r"}, 3, StringSplitOptions.RemoveEmptyEntries);
            if (lines.Length != 3)
                return;

            MouseMove -= ScreenSaverForm_MouseMove;
            KeyDown -= ScreenSaverForm_KeyDown;
            MouseDown -= ScreenSaverForm_MouseDown;

            Capture = false;
            Cursor.Show();
            ShowInTaskbar = true;
            TopMost = false;


            if (MessageBox.Show(lines[2], lines[0], MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                if(Uri.IsWellFormedUriString(lines[1], UriKind.Absolute))
                    Process.Start(lines[1]);
            }

            Close();
        }

        #region Nested type: RefreshCallback

        protected delegate void RefreshCallback();

        #endregion
    }
}